<template>
  <div class="app-container">

    <!-- 条件查询   -->
    <el-form :inline="true" :model="query" size="mini" >
      <el-form-item label="分类名称:">
        <el-input v-model.trim="query.labelName" placeholder="分类名称"></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.status" clearable filterable style="width:120px;" placeholder="请选择">
          <el-option value="2" label="禁用">禁用</el-option>
          <el-option value="1" label="正常">正常</el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" type="primary" @click="fetchLabelList">查询</el-button>
        <el-button icon="el-icon-refresh" @click="reload">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()" style="margin-bottom: 20px;">添加</el-button>
    <el-button size="small" type="danger" icon="el-icon-document-delete" @click="handleMultiDel()" style="margin-bottom: 20px;">删除</el-button>

    <!--  列表数据  -->
    <el-table :data="labelList" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange" tooltip-effect="dark">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column align="center" label="序号" width="80" type="index"></el-table-column>
      <el-table-column align="center" prop="labelName" label="标签名称" width="300" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="labelCode" label="标签代码" width="300" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 2" type="danger">禁用</el-tag>
          <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间" width="200">
        <template slot-scope="scope">
          {{ getFormat(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  align="center" label="操作" >
        <template slot-scope="scope">
          <el-button icon="el-icon-edit"
                     type="success" size="mini"
                     @click="handleEdit(scope.row.labelId)">编辑</el-button>
          <el-button icon="el-icon-document-delete" type="danger" size="mini" @click="handleDel(scope.row.labelId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div style="margin-top: 10px;">
      <el-pagination background
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="query.pageNo"
                     :page-sizes="[10, 20, 50]"
                     :page-size="query.pageSize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="query.total">
      </el-pagination>
    </div>

    <el-drawer :title="title" :visible.sync="drawerVisible" direction="rtl" :before-close="handleClose" :wrapper-closable="false">
      <el-form :model="labelData" ref="formData" label-width="120px" label-position="right" style="margin-right: 20px;">
        <el-form-item label="标签名称：" prop="labelName">
          <el-input v-model="labelData.labelName" placeholder="请输入标签名称" show-word-limit maxlength="20" clearable/>
        </el-form-item>
        <el-form-item label="标签代码：" prop="labelCode">
          <el-input v-model="labelData.labelCode" placeholder="请输入标签代码" show-word-limit maxlength="20" clearable/>
        </el-form-item>
        <el-form-item label="标签状态：" prop="status" v-if="title === '编辑标签'">
          <el-radio-group v-model="labelData.status">
            <el-radio :label = 2 border>禁用</el-radio>
            <el-radio :label = 1 border>正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-row style="margin-left: 40px">
        <el-button size="small" type="danger" plain @click="handleClose">取消</el-button>
        <el-button size="small" type="success" @click="submit()" :loading="loading">提交</el-button>
      </el-row>
    </el-drawer>

  </div>
</template>

<script>
import { dateFormat } from '@/utils/date';
import { list, createLabel, editLabel, deleteLabel, labelInfo } from "@/api/label";
import {deleteCategory} from "@/api/category";
export default {
  data() {
    return {
      query: {
        labelName: "",
        status: "",
        pageNo: 1,
        pageSize: 10,
        total: 0
      },
      labelList: [],
      title: "添加标签",
      drawerVisible: false,
      labelData: {
        labelName: "",
        labelCode: "",
        status: ""
      },
      loading: false,
      valid: true,
      checkedLabelIds: []
    }
  },

  created() {
    this.fetchLabelList();
  },

  methods: {
    // 查询标签列表
    fetchLabelList() {
      list(this.query).then(res => {
        if (res.code === 200) {
          this.labelList = res.data.list;
          this.query.total = res.data.total;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    submit() {
      this.beforeEditAndCreate();
      if (!this.valid) {
        this.valid = true;
        return;
      }

      this.loading = true;
      if (this.title === '编辑标签') {
        editLabel(this.labelData).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.loading = false;
          }
        })
      } else {
        createLabel(this.labelData).then(res => {
          if (res.code === 200) {
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 1500
            });
            this.handleClose();
          } else {
            this.$notify.error({
              title: '错误',
              message: res.message,
              duration: 1500
            });
            this.loading = false;
          }
        })
      }
    },

    beforeEditAndCreate() {
      if (!this.labelData.labelName) {
        this.$notify.error({
          title: '错误',
          message: '请输入标签名称',
          duration: 1500
        });
        this.valid = false;
        return;
      }

      if (!this.labelData.labelCode) {
        this.$notify.error({
          title: '错误',
          message: '请输入标签代码',
          duration: 1500
        });
        this.valid = false;
      }
    },

    handleAdd() {
      this.drawerVisible = true;
    },

    handleEdit(labelId) {
      labelInfo(labelId).then(res => {
        if (res.code === 200) {
          this.title = "编辑标签";
          this.drawerVisible = true;
          this.labelData = res.data;
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    handleSelectionChange(val) {
      let len = JSON.parse(JSON.stringify(val))
      this.checkedLabelIds = [];
      if (len.length !== 0) {
        for (let i = 0; i < len.length; i++) {
          this.checkedLabelIds.push(len[i].labelId)
        }
      } else {
        this.checkedLabelIds = len
      }
    },

    handleDel(labelId) {
      this.$confirm('确认删除这条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          labelIds: []
        }
        data.labelIds.push(labelId)
        deleteLabel(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchLabelList();
        })
      }).catch(() => {
        // 取消删除
      });
    },

    handleMultiDel() {
      if (this.checkedLabelIds.length === 0) {
        this.$notify.error({
          title: '错误',
          message: '请至少选择一个标签',
          duration: 1500
        });
        return;
      }

      this.$confirm('确认删除这些记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 发送删除请求
        const data = {
          labelIds: []
        }
        data.labelIds = this.checkedLabelIds;
        deleteLabel(data).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 1500
            });
          } else {
            this.$notify.error({
              title: '错误',
              message: response.message,
              duration: 1500
            });
          }
          // 刷新列表
          this.fetchLabelList();
          this.checkedLabelIds = []
        })
      }).catch(() => {
        // 取消删除
        this.checkedLabelIds = []
      });
    },

    reload() {
      this.query.labelName = "";
      this.query.status = "";
      this.query.scope = "";
      this.fetchLabelList();
    },

    // val 是切换之后的每页显示多少条
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.fetchLabelList();
    },

    // 当页码改变后触发此方法 val是当前点击（或输入）的页码
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.fetchLabelList();
    },

    // 格式化日期
    getFormat(date){
      return dateFormat(date);
    },

    // 关闭添加或编辑标签信息的弹窗
    handleClose() {
      this.labelData.labelName = "";
      this.labelData.labelCode = "";
      this.labelData.status = "";
      this.drawerVisible = false;
      this.title = "添加标签";
      this.loading = false;
      this.fetchLabelList();
    },
  }
}
</script>
